import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import {MqttMessage,MqttService,MqttConnectionState} from 'ngx-mqtt';
import { Observable } from 'rxjs/Observable';
/*
  Generated class for the MqttServiceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class MqttServiceProvider {

  constructor(public http: Http,private _mqttService: MqttService) {
    console.log('--开始MQTT监听--');

        this._mqttService.observe('/fw/alphair2/+/up').subscribe((message: MqttMessage) => {
           console.log(message.topic+':');
           console.log(message.payload.toLocaleString());
           
        });

        this._mqttService.state.subscribe((value)=>{
          switch(value){
            case MqttConnectionState.CLOSED:
              this.onLostConnection();
              break;
            case MqttConnectionState.CONNECTED:
              this.onConnected();
              break;
          }
        });
  }
  public unsafePublish(topic: string, message: any): void {
    this._mqttService.unsafePublish(topic, message, {qos: 0, retain: false});
  }


  onConnected(){
    console.log('Connected to broker');
  }
  onLostConnection(){
    console.log('Disconnected to broker');
  }
}
